######################################################################
# Time-stamp: <04/08/18 14:33:51 ostolop>
#
# object to create error XML files
######################################################################
package EP::Common::Query::ErrorBuilder;
use strict;

use XML::LibXML;

=head1 NAME

ErrorBuilder - responsible for building error XML documents

=head1 SYNOPSIS

my $error_builder = new ErrorBuilder;
$error_builder->add_error ( "Just informing you of something...", 1 );

=cut

my $epc_error_XML = <<__EPCERRORXML__;
<?xml version="1.0"?><epc_error/>
__EPCERRORXML__

=head1 METHODS

=cut

sub new {
  my $proto = shift;
  my $class = ref($proto) || $proto;
  my $self  = {};
  bless $self, $class;
  $self->initialize();
  return $self;
}

sub initialize {
  my $self = shift;

  my $parser = XML::LibXML->new();
  $self->{doc} = $parser->parse_string ( $epc_error_XML );

  if ($@) {
    error($@);
    die "Couldn't create document.";
  };

  return;
}

=over

=item add_error

Creates and adds an <error> element to the document. These elements
have a severity attribute, with values ranging from 1 to 3 (least to
most), and an error code, defined elsewhere. Also a message can be
contained within the <error> element.

=over

=item 1: information

=item 2: warning

=item 3: error

=back

=cut

sub add_error {
  my $self = shift;
  my ( $message, $err_code, $severity ) = @_;

  my $doc = $self->{doc};
  my $root = $doc->getDocumentElement();
  my $error = $doc->createElement ( "error" );
  $error->setAttribute ( "err_code", $err_code );
  $error->setAttribute ( "severity", $severity );
  $error->appendChild ( $doc->createTextNode ( $message ) );

  $root->appendChild ( $error );
}

=item toString

Converts the XML document to string (just calls the C<toString> method
on the document object)

=cut

sub toString {
  my $self = shift;
  return $self->{doc}->toString();
}

=item toFile

Converts the XML document to string and writes it to a file (just
calls the C<toFile> method on the document object)

=cut

######################################################################

sub toFile {
  my $self = shift;
  my $file = shift;
  return $self->{doc}->toFile($file);
}

=item getDocumentElement

Gets the document element for the doc. We are really wrapping this
around XML::LibXML::Document. Probably should just inherit from it.

=cut

######################################################################
sub getDocumentElement {
  my $self = shift;
  return $self->{doc}->getDocumentElement();
}

sub error {
  my $error = shift;
  print STDERR "Error in eval: ";
  if (ref $error) {
    print STDERR "msg: ", $error->getMessage();
    if (ref $error eq 'XML::Xerces::DOM_DOMException') {
      print STDERR "\n\tcode: ", $error->{code};
    }
  print STDERR "\n";
  } else {
    print STDERR $error;
  }
}

1;
